/*
* Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: btserver.cpp.
*/

#include <qrfcommserver.h>
#include <qbluetoothsocket.h>

#include <QtCore/QDebug>

#include "btserver.h"

BtServer::BtServer(QObject *parent)
    : QObject(parent), m_rfcommServer(0), m_clientSocket(0)
{
}

BtServer::~BtServer()
{
    delete m_clientSocket;
    delete m_rfcommServer;
}

void BtServer::startServer(const QBluetoothAddress &address, quint16 port)
{
    if (m_rfcommServer)
        return;

    // Create the server
    m_rfcommServer = new QRfcommServer(this);
    connect(m_rfcommServer, SIGNAL(newConnection()), this, SLOT(clientConnected()));
    bool ret = m_rfcommServer->listen( address, port );
    if ( !ret )
        qDebug( "Server is not able to start listening" );
}

void BtServer::closeClient()
{
    if ( m_clientSocket )
    {
        m_clientSocket->disconnectFromService();
        m_clientSocket->deleteLater();
        m_clientSocket = 0;
    }
}

void BtServer::clientConnected()
{
    qDebug() << "Client connected";
    m_clientSocket = m_rfcommServer->nextPendingConnection();

    if ( !m_clientSocket )
        return;

    connect(m_clientSocket, SIGNAL(readyRead()), this, SLOT(readSocket()));
    connect(m_clientSocket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));

    emit newClient( m_clientSocket->peerName() );
}

void BtServer::clientDisconnected()
{
    emit clientDisconnected( m_clientSocket->peerName() );
    m_clientSocket->deleteLater();
    m_clientSocket = 0;
}

void BtServer::readSocket()
{
    qDebug() << "BtServer::readSocket";
    if ( m_clientSocket )
    {
    qDebug() << "BtServer::readSocket - socket found, read data";
        if ( m_clientSocket->bytesAvailable() )
        {
            emit messageReceived( m_clientSocket->readAll() );
        }
    }
}

void BtServer::writeSocket(const QByteArray &sharedData)
{
    qDebug() << "BtServer::writeSocket";
    if ( m_clientSocket )
    {
        qDebug() << "BtServer::writeSocket - socket found, write data";
        m_clientSocket->write(sharedData);
    }
}
